package pl.edu.agh.portal.application.portlets;

import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import pl.edu.agh.portal.application.utils.PortletsUtils;
import pl.edu.agh.thesis.webservices.task.client.TaskManagerStub;
import pl.edu.agh.thesis.webservices.task.client.TaskUtils;

public class TaskRemovePortlet extends ThesisGenericPortlet {

	private static final String NORMAL_VIEW = "/task_remove_portlet.jsp";
	
	private PortletRequestDispatcher normalView;	
	
	private TaskManagerStub.Task task;
	
	public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
				
		String taskIdString = (String) PortletsUtils.vault.get("taskId");		
		int taskId = Integer.parseInt(taskIdString);
		
		task = TaskUtils.get(PortletsUtils.temp_session, taskId);
			
		request.setAttribute(PortletsUtils.ATTRIBUTE_TASK_FOR_REMOVE, task);
						
		normalView.include(request, response);
	}
	
	@Override
	public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
		
		String value = request.getParameter(PortletsUtils.TASK_REMOVE_KEY);		
		if (value.equals(PortletsUtils.BUTTON_CANCEL)) {
			response.sendRedirect("/portal/portal/task_list.psml");
		} else if (value.equals(PortletsUtils.BUTTON_REMOVE)) {
			TaskUtils.delete(PortletsUtils.temp_session, task);
			response.sendRedirect("/portal/portal/task_list.psml");						
		} else {
			response.setPortletMode(PortletMode.VIEW);
		}
	}	
	
	public void init(PortletConfig config) throws PortletException {
		super.init(config);
		normalView = config.getPortletContext().getRequestDispatcher(NORMAL_VIEW);
	}
	
	public void destroy() {
		normalView = null;
		super.destroy();
	}
	
}
